package com.hhhn.wk.main.tab4.address;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.main.tab4.address.entity.Address;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.AppValidationMgr;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.MD5Util;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.widget.select_address.bean.City;
import com.hhhn.wk.widget.select_address.bean.County;
import com.hhhn.wk.widget.select_address.bean.Province;
import com.hhhn.wk.widget.select_address.bean.Street;
import com.hhhn.wk.widget.select_address.utils.LogUtil;
import com.hhhn.wk.widget.select_address.widget.AddressSelector;
import com.hhhn.wk.widget.select_address.widget.BottomDialog;
import com.hhhn.wk.widget.select_address.widget.OnAddressSelectedListener;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/31 0031    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 新增收货地址
 * * * * * * * * * * * */
public class AddressAddActivity extends BaseActivity implements View.OnClickListener, OnAddressSelectedListener, AddressSelector.OnDialogCloseListener, AddressSelector.onSelectorAreaPositionListener  {
    private EditText et_name;//姓名
    private EditText et_phone;//手机号
    private RadioGroup mRadioGroup;//性别
    public RadioButton mRadio1, mRadio2;
    private int sex=0;//1男  2女
    private LinearLayout ll_selectAddress;//选择地址
    private TextView tv_address;//选择地址
    private String provinceCode;
    private String cityCode;
    private String countyCode;
    private String streetCode;
    private BottomDialog dialog;
    private EditText et_address;//详细地址
    private TextView tv_title;
    private BaseActivity activity;
    private Context  context;
    private Button btn_ok;
    private CheckBox mCheckBox;
    private int isCheckedShow=100902;  //0：代表默认，1代表 不是默认
    Intent intent=null;
    String title="";
    Address mAddress=null;

    String str_province="";
    String str_city="";
    String str_town="";
    String str_street="";

    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_address_add);
        activity=this;
        context=AddressAddActivity.this;
         intent=getIntent();
         title = intent.getStringExtra("title");
        if (title.equals("编辑收货地址")){
             mAddress = (Address) intent.getSerializableExtra("class");
        }
    }

    @Override
    protected void initView() {
        mCheckBox=findViewById(R.id.mCheckBox);
        ll_selectAddress=findViewById(R.id.ll_selectAddress);
        et_address=findViewById(R.id.et_address);
        et_phone=findViewById(R.id.et_phone);
        et_name=findViewById(R.id.et_name);
        tv_address=findViewById(R.id.tv_address);
        tv_title=findViewById(R.id.tv_title);
        btn_ok=findViewById(R.id.btn_ok);
        mRadioGroup=findViewById(R.id.mRadioGroup);
        mRadio1 =  findViewById(R.id.mRadioButton1);
        mRadio2 =  findViewById(R.id.mRadioButton2);
    }

    @Override
    protected void initData() {
        tv_title.setText(title);
        if (title.equals("编辑收货地址")){
            et_name.setText(mAddress.getName());
            et_phone.setText(mAddress.getPhone());
            tv_address.setText(mAddress.getProvince()+mAddress.getCity()+mAddress.getTown());
            et_address.setText(mAddress.getAddress());
            if (mAddress.getDef()==100901){
                mCheckBox.setChecked(true);
            }else {
                mCheckBox.setChecked(false);
            }
        }
    }

    @Override
    protected void initClick() {
        ll_selectAddress.setOnClickListener(this);
        //确定
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim_name = et_name.getText().toString().trim();
                String trim_phone = et_phone.getText().toString().trim();
                String trim_et_address = et_address.getText().toString().trim();
                String trim_tv_address = tv_address.getText().toString().trim();

                if (trim_name==null||"".equals(trim_name)){
                    toastWk("请输入联系人");
                    return;
                }
                if (trim_name.length()>10){
                    toastWk("联系人字符长度为30位");
                    return;
                }
                if (sex==0){
                    toastWk("请选择性别");
                    return;
                }
                if (trim_phone==null||"".equals(trim_phone)){
                    toastWk("请输入联系方式");
                    return;
                }
                if (!AppValidationMgr.isPhone(trim_phone)){
                    toastWk("手机号输入有误，请重新输入");
                    return;
                }
                if (trim_tv_address==null||"".equals(trim_tv_address)||"请选择".equals(trim_tv_address)){
                    toastWk("请输入城市");
                    return;
                }
                if (trim_et_address==null||"".equals(trim_et_address)){
                    toastWk("请输入详细地址");
                    return;
                }
                if (trim_et_address.length()>30){
                    toastWk("详细地址字符长度为30位");
                    return;
                }


                getJSON();
            }
        });

        //性别
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId){
                    case R.id.mRadioButton1:
                        sex=100201;
                        Log.d("sex", "onCheckedChanged: "+sex);
                        break;
                    case R.id.mRadioButton2:
                        sex=100202;
                        Log.d("sex", "onCheckedChanged: "+sex);
                        break;

                }
            }
        });

        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if(isChecked){
                    isCheckedShow=100901;
                    Log.d("isCheckedShow", "onCheckedChanged: "+isCheckedShow);
                }else{
                    isCheckedShow=100902;
                    Log.d("isCheckedShow", "onCheckedChanged: "+isCheckedShow);
                }
            }
        });
    }
    @Override
    public void onClick(View view) {
        if (dialog != null) {
            dialog.show();
        } else {
            dialog = new BottomDialog(this);
            dialog.setOnAddressSelectedListener(this);
            dialog.setDialogDismisListener(this);
            dialog.setTextSize(14);//设置字体的大小
            dialog.setIndicatorBackgroundColor(android.R.color.holo_red_dark);//设置指示器的颜色
            dialog.setTextSelectedColor(android.R.color.holo_red_dark);//设置字体获得焦点的颜色
            dialog.setTextUnSelectedColor(android.R.color.holo_red_dark);//设置字体没有获得焦点的颜色
//            dialog.setDisplaySelectorArea("31",1,"2704",1,"2711",0,"15582",1);//设置已选中的地区
            dialog.setSelectorAreaPositionListener(this);
            dialog.show();
        }
    }
    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        provinceCode = (province == null ? "" : province.code);
        cityCode = (city == null ? "" : city.code);
        countyCode = (county == null ? "" : county.code);
        streetCode = (street == null ? "" : street.code);
//        LogUtil.d("数据", "省份id=" + provinceCode);
//        LogUtil.d("数据", "城市id=" + cityCode);
//        LogUtil.d("数据", "乡镇id=" + countyCode);
//        LogUtil.d("数据", "街道id=" + streetCode);

        Log.d("数据", "省份id=" + provinceCode);
        Log.d("数据", "城市id=" + cityCode);
        Log.d("数据", "乡镇id=" + countyCode);
        Log.d("数据", "街道id=" + streetCode);
        Log.d("", "onAddressSelected: ");
        String s = (province == null ? "" : province.name) + (city == null ? "" : city.name) + (county == null ? "" : county.name) +
                (street == null ? "" : street.name);
        tv_address.setText(s);

         str_province=province == null ? "" : province.name;
         str_city=city == null ? "" : city.name;
         str_town=county == null ? "" : county.name;
        str_street=street == null ? "" : street.name;

        if (dialog != null) {
            dialog.dismiss();
        }
//        getSelectedArea();
    }
    @Override
    public void dialogclose() {
        if(dialog!=null){
            dialog.dismiss();
        }
    }
    @Override
    public void selectorAreaPosition(int provincePosition, int cityPosition, int countyPosition, int streetPosition) {
//        this.provincePosition = provincePosition;
//        this.cityPosition = cityPosition;
//        this.countyPosition = countyPosition;
//        this.streetPosition = streetPosition;
//        LogUtil.d("数据", "省份位置=" + provincePosition);
//        LogUtil.d("数据", "城市位置=" + cityPosition);
//        LogUtil.d("数据", "乡镇位置=" + countyPosition);
//        LogUtil.d("数据", "街道位置=" + streetPosition);
    }



    //新增收货地址
    public void getJSON() {
        showLoad();
        RequestParams params ;

        if (title.equals("编辑收货地址")){
             params = AllPublic.getParams(activity, "/updateShipAddress", false);
        }else {
             params = AllPublic.getParams(activity, "/saveShipAddress", false);
        }
//        userId	用户Id	int	是	用户Id

//        address	地址	String	是	地址
//        phone	手机号	String	是	联系人手机
//        userName	联系人	String	是	联系人
//        sex	性别	String	是	性别（1：男，2：女）
//        city	城市	String	是	city
//        isShow	是否默认	String	是	0：代表默认，1代表 不是默认
        params.addParameter("cmUserId",getUser().getUid());/*用户Id*/
        params.addParameter("address",str_street+et_address.getText().toString().trim());//地址
        params.addParameter("shipTel",et_phone.getText().toString().trim());//手机号
        params.addParameter("shipName",et_name.getText().toString().trim());//联系人
        params.addParameter("shipSex",sex);//性别（1：男，2：女）

        params.addParameter("provinces",str_province);//城市
        params.addParameter("citys",str_city);//城市
        params.addParameter("towns",str_town);//城市


        params.addParameter("isDefault",isCheckedShow);//0：代表默认，1代表 不是默认
        Log.d("新增收货地址", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("新增收货地址：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {

                        Toast.makeText(context, "新增收货地址成功", Toast.LENGTH_SHORT).show();

                        setResult(1,intent);
                        finish();
                    }else {
                     toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }
}
